import { HttpService, Injectable } from '@nestjs/common';
import { AxiosResponse } from 'axios';

@Injectable()
export class FetchService {

  private readonly baidukey: string;
  private readonly tencentkey: string;

  constructor(private readonly httpService: HttpService) {
    this.baidukey = 'sg0bzim3K77UKXGSnulWU2G8o2wzI7S6';
    this.tencentkey = 'FVABZ-VOVWQ-FJ55C-G3OJH-AMUXH-AUFSK';
  }

  async getPositionByTencent(lat, lng): Promise<AxiosResponse<any>> {
    return this.httpService.get('https://apis.map.qq.com/ws/geocoder/v1', {
      params: {
        location: `${lat},${lng}`,
        key: this.tencentkey
      }
    }).toPromise();
  }

  async searchPlaceForKeywordByTencent(keyword, cityName): Promise<AxiosResponse<any>> {
    return this.httpService.get('https://apis.map.qq.com/ws/place/v1/search', {
      params: {
        keyword: encodeURI(keyword),
        boundary: `region(${cityName}, 0)`,
        page_size: 10,
        key: this.tencentkey
      }
    }).toPromise();
  }

  async getLocationForIpByTencent(ip): Promise<AxiosResponse<any>> {
    return this.httpService.get('https://apis.map.qq.com/ws/location/v1/ip', {
      params: {
        ip,
        key: this.tencentkey
      }
    }).toPromise();
  }

  async getLocationForIpByBaidu(ip): Promise<AxiosResponse<any>> {
    return this.httpService.get('http://api.map.baidu.com/location/ip', {
      params: {
        ip,
        ak: this.baidukey
      }
    }).toPromise();
  }

  async getDistanceForRiding(from, to): Promise<AxiosResponse<any>> {
    return this.httpService.get('http://api.map.baidu.com/routematrix/v2/riding', {
      params: {
        ak: this.baidukey,
        origins: from,
        destinations: to,
        output: 'json'
      }
    }).toPromise();
  }

}